package com.ai.huggingFace;

/**
 * @author houwenpeng
 */
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import okhttp3.*;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;

/**
 *
 * Hugging Face API 示例
 *
 * @author houwenpeng
 */
public class HuggingFaceApiExample {
    private static final String API_URL = "https://api-inference.huggingface.co/models/gpt2"; // 使用 GPT-2 模型


    @Value("${chat.huggingface-key}")
    private static String API_KEY;

    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient();

        JsonObject json = new JsonObject();
        json.addProperty("inputs", "Hello, world");

        RequestBody body = RequestBody.create(json.toString(), MediaType.get("application/json; charset=utf-8"));

        Request request = new Request.Builder()
                .url(API_URL)
                .header("Authorization", "Bearer " + API_KEY)
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            String responseBody = response.body().string();

            // 解析 JSON 响应
            Gson gson = new Gson();
            JsonArray jsonArray = gson.fromJson(responseBody, JsonArray.class);
            JsonObject result = jsonArray.get(0).getAsJsonObject();
             result.get("generated_text").getAsString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /*public static void main(String[] args) {
        try {
            // 创建 HTTP 客户端
            CloseableHttpClient httpClient = HttpClients.createDefault();

            // 创建 POST 请求
            HttpPost post = new HttpPost(API_URL);
            post.setHeader("Authorization", "Bearer " + "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");
            post.setHeader("Content-Type", "application/json");

            // 设置请求体
            JsonObject requestBody = new JsonObject();
            requestBody.addProperty("inputs", "你好?");
            StringEntity entity = new StringEntity(requestBody.toString());
            post.setEntity(entity);

            // 执行请求并获取响应
            HttpEntity responseEntity = httpClient.execute(post).getEntity();
            String response = EntityUtils.toString(responseEntity);

            // 输出响应
            System.out.println("Response: " + response);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/
}
